<template>
  <div class="app-container">
    <el-page-header @back="goBack" content="添加页面">
    </el-page-header>
    <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="170px" style="width: 100%;  padding-top: 62px;margin-left:50px;">
      <el-form-item label="模块类型" prop="module_type" >
        <el-select v-model="addData.module_type" placeholder="请选择类型"  @change="handleModuleTypeChange">
          <el-option
            v-for="(item, i) in moduleTypeOptions"
            :key="i"
            :label="item.title"
            :value="item.type">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模块标题" prop="title">
        <el-input v-model="addData.title" style="width: 380px;" />
      </el-form-item>
      <el-form-item label="模块Sign" prop="sign">
        <el-input v-model="addData.sign" style="width: 380px;" />
      </el-form-item>
      <el-form-item label="模块描述" prop="mark">
        <el-input v-model="addData.mark" style="width: 380px;" />
      </el-form-item>
      <el-form-item label="模块图片" prop="image_list" v-if="currentModuleType === 1">
        <el-upload
          class="avatar-uploader"
          :action="imageUploadUrl"
          list-type="picture-card"
          :headers="uploadHeader"
          :file-list="editInitImageList"
          :before-upload="beforeAvatarUpload"
          :on-success="handleUploadListImageSuccess"
          :on-preview="handleImagePreview"
          :on-remove="handleImageRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <div>
          <el-input v-for="(item, index) in linkInputList" :key="item.key" v-model="addData.link_list[index]" style="width: 150px; margin-right: 5px;" />
        </div>
        <el-dialog :visible.sync="dialogImagePreviewVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item
        v-if="currentModuleType === 2"
        label='模块内容'
      >
        <el-input
          v-for="(item, i) in nodeInputList"
          :key="item.key"
          style="width: 150px;margin-right: 5px;"
          v-model="addData.node_list[i]"
        ></el-input>
        <el-button icon="el-icon-plus" @click.prevent="addNodeListInput(item)"></el-button>
        <el-button icon="el-icon-minus" @click.prevent="removeNodeListInput(item)"></el-button>
      </el-form-item>
    </el-form>
    <div style="margin-top: 20px; margin-right:30px;float: right;">
      <el-button type="primary" @click="handleAddSubmit()">
        提交
      </el-button>
    </div>
  </div>
</template>

<script>
import { systemModuleAdd, systemModuleDetail, systemModuleImageUpload } from '@/api/system'
import waves from '@/directive/waves'
import { getToken } from '@/utils/auth'
import { strLength } from '@/utils/common'

export default {
  name: 'SystemModuleAdd',
  directives: { waves },
  data() {
    const checkTitle = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 标题不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 64 || strLen < 6) {
        return callback(new Error('对不起， 标题长度为6-64个字符,汉字为3个字符!'))
      } else {
        callback()
      }
    }
    const checkSummary = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 摘要不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 64 || strLen < 6) {
        return callback(new Error('对不起， 摘要长度为6-64个字符,汉字为3个字符!'))
      } else {
        callback()
      }
    }
    return {
      // 副文本配置
      customConfig: {
        body_class: 'node_id',
        height: 500,
        plugins: 'image',
        toolbar: 'image',
        images_upload_url: '',
        images_upload_handler: function(blobInfo, success, failure) {
          const imageData = new FormData()
          imageData.append('file', blobInfo.blob(), blobInfo.filename())
          systemModuleImageUpload(imageData).then(res => {
            if (res.success) {
              success(res.data.file_url)
            }
          })
        }
      },
      nodeInputList: [{
        value: '',
        key: Date.now()
      }],
      linkInputList: [],
      imageRelateLinkList: [],
      editInitImageList: [],
      imageCoverUrl: '',
      dialogImageUrl: '',
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'system/modules/imageUpload',
      dialogImagePreviewVisible: false,
      currentAction: 'add',
      currentModuleType: 1,
      addData: {
        id: '0',
        title: '',
        module_type: 1,
        sign: '',
        image_list: [],
        link_list: [],
        node_list: [],
        start_time: '',
        end_time: '',
        mark: ''
      },
      tmpSelectedPid: 0,
      moduleTypeOptions: [],
      rules: {
        title: [{ validator: checkTitle, trigger: 'blur' }, { required: true, message: '需要填写标题', trigger: 'blur' }],
        module_type: [{ required: true, message: '需要选择模块类型', trigger: 'blur' }],
        sign: [{ required: true, message: '需要填写标识', trigger: 'blur' }],
        mark: [{ validator: checkSummary, trigger: 'blur' }, { required: true, message: '需要填写摘要', trigger: 'blur' }]
      }
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  created() {
    this.resetAddData()
    systemModuleDetail(this.$route.params.id).then((response) => {
      if (response.success) {
        this.moduleTypeOptions = response.data.module_type_option
        if (this.$route.params.id > 0) {
          this.addData = response.data.item
          this.currentModuleType = response.data.item.module_type
          this.editInitImageList = this.addData.image_list_arr
          this.initLinkInput()
          console.log(this.currentModuleType)
          console.log(this.addData)
        }
      }
    }).catch(err => {
      console.log(err)
    })
    this.$nextTick(() => {
      this.$refs['addForm'].clearValidate()
    })
  },
  methods: {
    resetAddData() {
      this.imageCoverUrl = ''
      this.addData = {
        id: '0',
        title: '',
        module_type: 1,
        sign: '',
        image_list: [],
        link_list: [],
        node_list: [],
        start_time: '',
        end_time: '',
        mark: ''
      }
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          if (this.addData.content === '') {
            this.$message({
              type: 'error',
              message: '对不起, 内容不能为空!!'
            })
            return
          }
          this.addData.image_list = this.addData.image_list.join(',')
          this.addData.link_list = this.addData.link_list.join(',')
          this.addData.node_list = this.addData.node_list.join(',')
          systemModuleAdd(this.addData).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: '添加成功!'
              })
              setTimeout(() => {
                const view = this.$route
                this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
                })
                this.$router.push({ path: '/admin/modules/list' })
              }, 1 * 200)
            }
          }).catch(err => {
            console.log(err)
          })
        }
      })
    },
    beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传封面图片只能是 JPG/PNG 格式!')
        return false
      }

      if (file.size / 1024 > 300) {
        this.$message.error('上传封面图片大小不能超过 300K!')
        return false
      }
      return true
    },
    handleUploadListImageSuccess(res, file, fileList) {
      if (res.success) {
        const imageNameList = []
        for (let i = 0; i < fileList.length; i++) {
          if ('image_name' in fileList[i]) {
            imageNameList.push(fileList[i].image_name)
          } else {
            imageNameList.push(fileList[i].response.data.file_name)
          }
        }
        this.addData.image_list = imageNameList
        this.addLinkInput(file.response.data.file_name)
        this.sortLinkInput()
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    handleImageRemove(file, fileList) {
      const imageNameList = []
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].hasOwnProperty('response')) {
          imageNameList.push(fileList[i].response.data.file_name)
        } else {
          imageNameList.push(fileList[i].image_name)
        }
      }
      this.addData.image_list = imageNameList

      this.sortLinkInput()
    },
    handleImagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImagePreviewVisible = true
    },
    goBack() {
      this.$router.push({ path: '/admin/modules/list' })
    },
    initLinkInput() {
      for (let i = 0; i < this.addData.image_list.length; i++) {
        this.imageRelateLinkList[this.addData.image_list[i]] = {
          value: this.addData.link_list[i],
          key: Date.now()
        }
      }
      this.sortLinkInput()
    },
    sortLinkInput() {
      this.linkInputList = []
      this.addData.link_list = []
      for (let i = 0; i < this.addData.image_list.length; i++) {
        const item = this.imageRelateLinkList[ this.addData.image_list[i]]
        this.linkInputList.push(item)
        this.addData.link_list.push(item.value)
      }
    },
    addLinkInput(filename) {
      this.imageRelateLinkList[filename] = {
        value: '',
        key: Date.now()
      }

      for (let i = 0; i < this.addData.image_list.length; i++) {
        this.linkInputList.push(this.imageRelateLinkList[ this.addData.image_list[i]])
      }
    },
    // 内容相关
    addNodeListInput() {
      this.nodeInputList.push({
        value: '',
        key: Date.now()
      })
    },
    removeNodeListInput(item) {
      const index = this.nodeInputList.indexOf(item)
      if (index !== -1) {
        this.nodeInputList.splice(index, 1)
      }
    },
    handleModuleTypeChange(id) {
      this.currentModuleType = id
    }
  }
}
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .el-upload-list--picture-card {
    width: 150px;
    height: 150px;
  }
</style>
